package com.qyhl.module_practice.substreet.detail;

import android.annotation.SuppressLint;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.google.android.material.appbar.AppBarLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.makeramen.roundedimageview.RoundedImageView;
import com.qyhl.module_practice.R;
import com.qyhl.module_practice.R2;
import com.qyhl.module_practice.activity.PracticeActFragment;
import com.qyhl.module_practice.substreet.trend.PracticeTrendFragment;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.NetUtil;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.constant.ServicePathConstant;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeAlbumBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeListBean;
import com.qyhl.webtv.commonlib.entity.civilized.PracticeTeamBean;
import com.qyhl.webtv.commonlib.service.NewsService;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.expandableView.text.ExpandableTextView;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;


@Route(path = ARouterPathConstant.PRACTICE_STREET_DETAIL)
public class StreetDetailActivity extends BaseActivity implements StreetDetailContract.StreetDetailView {
    @BindView(R2.id.score)
    TextView score;
    @BindView(R2.id.summary)
    ExpandableTextView summary;
    @BindView(R2.id.exhibition_rv)
    RecyclerView exhibitionRv;
    @BindView(R2.id.exhibition_layout)
    CardView exhibitionLayout;
    @BindView(R2.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.view_pager)
    ViewPager viewPager;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.toolbar)
    Toolbar toolbar;
    @BindView(R2.id.btn_error_back)
    ImageView btnErrorBack;
    @BindView(R2.id.appBar)
    AppBarLayout appBar;
    @BindView(R2.id.team_rv)
    RecyclerView teamRv;
    @BindView(R2.id.team_layout)
    CardView teamLayout;

    private StreetDetailPresenter mPresenter;

    private String titleName;

    private String streetId;

    private String instId;

    private int volStatus;

    private String volId;

    private CommonAdapter commonAdapter;

    private CommonAdapter<PracticeTeamBean> teamAdapter;

    private List<PracticeTeamBean> teamList = new ArrayList<>();

    private List<PracticeAlbumBean> mPhotoList = new ArrayList<>();

    /**
     * 新闻服务
     */
    @Autowired(name = ServicePathConstant.NEWS_SERVICE)
    public NewsService newsService;

    private enum CollapsingToolbarLayoutState {
        EXPANDED,
        COLLAPSED,
        INTERNEDIATE
    }

    private CollapsingToolbarLayoutState state;


    @Override
    protected int getContentView() {
        return R.layout.practice_activity_street_detail;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.statusBarColor(R.color.white).statusBarDarkFont(true).fitsSystemWindows(true).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        titleName = getIntent().getStringExtra("title");
        instId = getIntent().getStringExtra("instId");
        volId = getIntent().getStringExtra("volId");
        streetId = getIntent().getStringExtra("streetId");
        volStatus = getIntent().getIntExtra("status", 0);

        mPresenter = new StreetDetailPresenter(this);
        loadMask.setStatus(LoadingLayout.Loading);

        btnErrorBack.setVisibility(View.GONE);

        //设置标题
        title.setText(titleName);

        setSupportActionBar(toolbar);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        exhibitionRv.setLayoutManager(linearLayoutManager);

        exhibitionRv.setAdapter(commonAdapter = new CommonAdapter<PracticeAlbumBean>(this, R.layout.practice_item_street_albums, mPhotoList) {
            @Override
            protected void convert(ViewHolder holder, PracticeAlbumBean bean, int position) {
                RoundedImageView cover = holder.getView(R.id.cover);
                Glide.with(StreetDetailActivity.this)
                        .load(bean.getThumbPath())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                        .into(cover);
            }
        });

        teamRv.setLayoutManager(new LinearLayoutManager(this));
        DividerItemDecoration divider = new DividerItemDecoration(this, DividerItemDecoration.VERTICAL);
        divider.setDrawable(Objects.requireNonNull(ContextCompat.getDrawable(this, R.drawable.practice_item_divider)));
        teamRv.addItemDecoration(divider);
        teamRv.setAdapter(teamAdapter = new CommonAdapter<PracticeTeamBean>(this, R.layout.practice_item_street_detail_team, teamList) {
            @Override
            protected void convert(ViewHolder holder, PracticeTeamBean bean, int position) {
                holder.setText(R.id.title, bean.getName());

                if (StringUtils.isNotEmpty(bean.getContactName())) {
                    holder.setVisible(R.id.name, true);
                    holder.setText(R.id.name, "负责人：" + bean.getContactName());
                } else {
                    holder.setVisible(R.id.name, false);
                }

                if (StringUtils.isNotEmpty(bean.getContactPhone())) {
                    holder.setVisible(R.id.contact, true);
                    holder.setText(R.id.contact, "联系方式：" + bean.getContactPhone());
                } else {
                    holder.setVisible(R.id.contact, false);
                }

                if (StringUtils.isEmpty(bean.getContactName()) && StringUtils.isEmpty(bean.getContactPhone())) {
                    holder.setVisible(R.id.contact_layout, false);
                } else {
                    holder.setVisible(R.id.contact_layout, true);
                }
            }
        });

        mPresenter.getDetail(streetId);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getDetail(streetId);
            }
        });

        teamAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {

                Bundle bundle = new Bundle();
                bundle.putString("orgId", teamList.get(position).getId() + "");
                bundle.putString("volId", volId);
                bundle.putString("instId", instId);
                RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_DETAIL, bundle);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                ArrayList<String> result = new ArrayList<>();
                for (int i = 0; i < mPhotoList.size(); i++) {
                    result.add(mPhotoList.get(i).getImagePath());
                }
                MNImageBrowser.showImageBrowser(StreetDetailActivity.this, view, position, result);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        //折叠状态监听
        appBar.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {

                if (verticalOffset == 0) {
                    if (state != CollapsingToolbarLayoutState.EXPANDED) {
                        state = CollapsingToolbarLayoutState.EXPANDED;//修改状态标记为展开
                    }
                } else if (Math.abs(verticalOffset) >= appBarLayout.getTotalScrollRange()) {
                    if (state != CollapsingToolbarLayoutState.COLLAPSED) {
                        state = CollapsingToolbarLayoutState.COLLAPSED;//修改状态标记为折叠
                    }
                } else {
                    if (state != CollapsingToolbarLayoutState.INTERNEDIATE) {
                        state = CollapsingToolbarLayoutState.INTERNEDIATE;//修改状态标记为中间
                    }
                }
            }
        });

    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setDetail(PracticeListBean bean) {
        btnErrorBack.setVisibility(View.GONE);
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");

        if (bean.getAlbums() != null && bean.getAlbums().size() > 0) {
            exhibitionLayout.setVisibility(View.VISIBLE);
            mPhotoList.clear();
            mPhotoList.addAll(bean.getAlbums());
            commonAdapter.notifyDataSetChanged();
        } else {
            exhibitionLayout.setVisibility(View.GONE);
        }

        if (bean.getOrgs() != null && bean.getOrgs().size() > 0) {
            teamLayout.setVisibility(View.VISIBLE);
            teamList.clear();
            if (bean.getOrgs().size() < 4) {
                teamList.addAll(bean.getOrgs());
            } else {
                for (int i = 0; i < 4; i++) {
                    teamList.add(bean.getOrgs().get(i));
                }
            }
            teamAdapter.notifyDataSetChanged();
        } else {
            teamLayout.setVisibility(View.GONE);
        }

        //描述设置
        summary.setText(bean.getInformation());


        //设置评分
        Typeface fontFace = Typeface.createFromAsset(getAssets(),
                "fonts/ReductoCondSSK.ttf");
        score.setTypeface(fontFace);
        score.setText(bean.getScore() + "");

        List<String> nameList = new ArrayList<>();
        List<Fragment> fragments = new ArrayList<>();

        for (int i = 0; i < bean.getCatalogs().size(); i++) {
            nameList.add(bean.getCatalogs().get(i).getCatalogName());
            switch (bean.getCatalogs().get(i).getType()){
                case 1:
                    fragments.add(newsService.getNewListFragment(bean.getCatalogs().get(i).getCatalogId()));
                    break;
                case 2:
                    break;
                case 3:
                    fragments.add(PracticeTrendFragment.newInstance(bean.getId() + "", false));
                    break;
                case 4:
                    fragments.add(PracticeActFragment.newInstance(streetId, 1, instId, ""));
                    break;
            }
        }

        viewPager.setAdapter(new Adapter(this.getSupportFragmentManager(), fragments, nameList));
        tabLayout.setViewPager(viewPager);
        tabLayout.getTitleView(0).getPaint().setFakeBoldText(true);

    }

    @Override
    public void setError(String msg) {
        btnErrorBack.setVisibility(View.VISIBLE);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setReloadButtonText("点击重试~");
        if (!NetUtil.isNetworkAvalible(this)) {
            loadMask.setErrorImage(R.drawable.error_network);
            loadMask.setErrorText("网络异常，请检查您的网络！");
        } else if (msg.contains("暂无")) {
            loadMask.setErrorImage(R.drawable.empty_content);
            loadMask.setErrorText(msg);
        } else {
            loadMask.setErrorImage(R.drawable.error_content);
            loadMask.setErrorText(msg);
        }
    }

    @OnClick({R2.id.exhibition_more, R2.id.btn_error_back, R2.id.team_more})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.exhibition_more) {
            ArrayList<String> result = new ArrayList<>();
            for (int i = 0; i < mPhotoList.size(); i++) {
                result.add(mPhotoList.get(i).getImagePath());
            }
            MNImageBrowser.showImageBrowser(StreetDetailActivity.this, view, 0, result);
        } else if (id == R.id.btn_error_back) {
            finish();
        } else if (id == R.id.team_more) {
            Bundle bundle = new Bundle();
            bundle.putString("instId", instId);
            bundle.putString("streetId", streetId);
            bundle.putString("volId", volId);
            bundle.putInt("status", volStatus);
            bundle.putBoolean("isStreet", true);
            RouterManager.router(ARouterPathConstant.PRACTICE_TEAM_LIST, bundle);

        }
    }


    class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> names;

        Adapter(FragmentManager fm, List<Fragment> fragmentList, List<String> names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names.get(position);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (android.R.id.home == item.getItemId()) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void collapsed() {
        if (state == CollapsingToolbarLayoutState.COLLAPSED) {
            appBar.setExpanded(true, true);
        }
    }

    public void expanded() {
        if (state == CollapsingToolbarLayoutState.EXPANDED) {
            appBar.setExpanded(false, true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        ActionLogUtils.getInstance().onResume(this, ActionConstant.PRACTICE_STREET_DETAIL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        ActionLogUtils.getInstance().onPause(this, ActionConstant.PRACTICE_STREET_DETAIL);
    }

}
